<template>
  <l-dialog
    :title="`${name}`"
    :visible.sync="midVisible"
    :hasBtns="false"
    :height="520"
    :width="width"
    @opened="handleOpened"
    @closed="handleClosed"
  >
    <l-layout class="l-tab-page" :right="394">
      <l-layout class="l-chat-box" :bottom="200">
        <div class="l-rblock" style="background: #fff; overflow: auto" ref="msgList">
          <div :class="['l-chat-box-msg-item', { me: isMe(item) }]" v-for="(item, index) in msgList" :key="index">
            <el-avatar :size="36" :src="avatar(item.f_SendUserId)" class="l-chat-box-avatar">
              <img :src="`${rootUrl}img/admin/head.png`" />
            </el-avatar>
            <div class="l-chat-box-msg-title" v-if="!isMe(item)">
              {{ getName(item.f_SendUserId) }}<span class="time">{{ getTime(item.f_CreateDate) }}</span>
            </div>
            <div class="l-chat-box-msg-title" v-else>
              <span class="time">{{ getTime(item.f_CreateDate) }}</span
              >{{ getName(item.f_SendUserId) }}
            </div>
            <div class="l-chat-box-msg-content">
              <div class="arrow"></div>
              {{ item.f_Content }}
            </div>
          </div>
        </div>
        <template #bottom>
          <l-layout :top="30" :topMove="false">
            <template #top>
              <div class="l-rblock l-chat-box-bar">
                <el-button icon="el-icon-time" @click="openHistroy">聊天记录</el-button>
              </div>
            </template>
            <textarea class="l-chat-box-textarea" :placeholder="$t('请输入消息')" v-model="msg" @keyup.enter="sendChat">
            </textarea>
          </l-layout>
        </template>
      </l-layout>
      <template #right>
        <chat-histroy v-if="histroyVisible" :otherId="otherId"></chat-histroy>
      </template>
    </l-layout>
  </l-dialog>
</template>
<script>
import ChatHistroy from "./chatHistroy.vue";
export default {
  name: "chat-box",
  inject: ["top"],
  props: {
    visible: {
      type: Boolean,
    },
    otherId: String,
    updateList: Function,
  },
  components: {
    ChatHistroy,
  },
  data() {
    return {
      msg: "",
      histroyVisible: false,
      msgList: [],
    };
  },
  created() {},
  mounted() {},
  computed: {
    midVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
    width() {
      if (this.histroyVisible) {
        return 960;
      } else {
        return 560;
      }
    },
    name() {
      return this.getName(this.otherId);
    },
    revList() {
      return this.$store.state.message.msg.map[this.otherId] || [];
    },
  },
  watch: {
    revList(val) {
      if (this.midVisible) {
        this.addMsg(val);
      }
    },
  },
  methods: {
    openHistroy() {
      this.histroyVisible = !this.histroyVisible;
    },
    async sendChat() {
      const msg = this.msg.replace("\n", "");
      this.msg = "";
      if (!msg) {
        return;
      }
      const postData = {
        f_SendUserId: this.loginInfo.f_UserId,
        f_RecvUserId: this.otherId,
        f_Content: msg,
        f_CreateDate: this.$getDayTime("yyyy-MM-dd HH:mm:ss"),
        f_MsgId: this.$uuid(),
        f_IsSystem: 0,
      };

      // 添加消息列表数据
      this.addMsg([postData]);

      this.updateList(this.otherId, msg, postData.f_CreateDate);

      const api = window.$api.message.msg;
      const res = await this.$awaitWraper(api.add(postData));
      this.top.sendChat(this.otherId, postData.f_Content, res);
    },
    addMsg(list) {
      const addList = list.filter((t) => this.msgList.findIndex((t2) => t.f_MsgId == t2.f_MsgId) == -1);
      this.msgList.push(...addList);

      this.msgList = this.msgList.sort((a, b) => {
        return Date.parse(a.f_CreateDate) - Date.parse(b.f_CreateDate);
      });

      this.$nextTick(() => {
        this.$refs.msgList.scrollTop = this.$refs.msgList.scrollHeight;
      });
      //console.log(this.$refs.msgList.scrollTop,this.$refs.msgList.scrollHeight)
    },
    async loadMsg() {
      const queryData = {
        rows: 30,
        page: 1,
        sidx: "F_CreateDate DESC",
        toId: this.otherId,
        sendId: this.loginInfo.f_UserId,
      };
      // 获取聊天记录
      const api = window.$api.message.msg;
      const data = (await this.$awaitWraper(api.getPage(queryData))) || {};
      this.addMsg(data.rows || []);
    },
    async handleOpened(showLoading, hideLoading) {
      showLoading("聊天数据加载中");
      await this.loadMsg();
      hideLoading();
    },
    handleClosed() {
      this.msgList = [];
    },

    isMe(item) {
      if (item.f_SendUserId != this.loginInfo.f_UserId) {
        return false;
      }
      return true;
    },
    getName(id) {
      //
      if (id == this.loginInfo.f_UserId) {
        return "我";
      }
      const user = this.lr_users[id];
      if (user) {
        let res = user.f_RealName;
        if (user.f_DepartmentId) {
          this.lr_loadDepartment(user.f_DepartmentId);
          const department = this.lr_department[user.f_DepartmentId];
          if (department) {
            res += `/${department.f_FullName}`;
          }
        }
        return res;
      } else {
        return " ";
      }
    },
    getTime(time) {
      const nowDate = this.$getDayTime("yyyy-MM-dd");
      const myDate = this.$formatDate(time, "yyyy-MM-dd");
      if (nowDate != myDate) {
        return this.$formatDate(time, "yyyy-MM-dd HH:mm:ss");
      } else {
        return this.$formatDate(time, "HH:mm:ss");
      }
    },
    avatar(id) {
      let user = null;
      if (id == this.loginInfo.f_UserId) {
        user = this.loginInfo;
      } else {
        user = this.lr_users[id];
      }

      if (user) {
        return user.f_HeadIcon
          ? `${this.apiUrl}organization/user/img/${user.f_HeadIcon}?token=${this.token}`
          : `${this.rootUrl}img/admin/head.png`;
      }
      return `${this.rootUrl}img/admin/head.png`;
    },
  },
};
</script>

<style lang="scss">
.l-chat-box {
  &-bar {
    background-color: #f0f2f5;
    text-align: right;
    .el-button {
      border: 0;
      background-color: #f0f2f5 !important;
      padding: 6px;
    }
  }
  &-textarea {
    width: 100%;
    height: 100%;
    resize: none;
    border: 0;
    outline: 0;
    padding: 4px;
    background: #fff;

    box-sizing: border-box;

    color: #333;
  }

  &-msg-item {
    position: relative;
    font-size: 0;
    margin-bottom: 8px;
    min-height: 64px;
    padding-left: 64px;
    padding-top: 14px;
    padding-right: 8px;
    text-align: left;
  }
  &-avatar {
    position: absolute;
    top: 14px;
    left: 14px;
  }

  &-msg-title {
    font-size: 12px;
    white-space: nowrap;
    color: #999;
    margin-bottom: 4px;

    .time {
      margin-left: 4px;
    }
  }

  &-msg-content {
    position: relative;
    font-size: 14px;
    color: #333;

    background: #f3f3f3;
    padding: 8px;
    border-radius: 4px;
    display: inline-block;

    .arrow {
      width: 8px;
      height: 8px;
      border: 1px solid #f3f3f3;
      transform: rotate(-45deg);
      background: #f3f3f3;
      position: absolute;
      top: 50%;
      left: -4px;
      margin-top: -7px;
      z-index: 1;
      clip: rect(0, 8px, 8px, 0);
      border-top: 0;
      border-left: 0;
    }
  }

  &-msg-item.me {
    padding-left: 8px;
    padding-right: 64px;
    text-align: right;
  }

  .me &-msg-content {
    color: #fff;
    background: #409eff;
    .arrow {
      border: 1px solid #409eff;
      background: #409eff;
      left: auto;
      right: -6px;
    }
  }

  .me &-avatar {
    left: auto;
    right: 14px;
  }
  .me &-msg-title {
    text-align: right;
    .time {
      margin-right: 4px;
    }
  }
}
</style>
